package com.yulang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yulang.entity.SysRole;
import com.yulang.entity.SysUser;
import com.yulang.mapper.SysRoleMapper;
import com.yulang.security.result.Result;
import com.yulang.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class SystemUserController {


    public final static String HTML_PREFIX = "system/user";

    @Autowired
    private SysRoleMapper sysRoleMapper;


    @Autowired
    private SysUserService service;

    @PreAuthorize("hasAnyAuthority('sys:user')")
    @GetMapping(value = {"/",""})
    public String user() {
        return HTML_PREFIX+"/user-list";
    }

    @PreAuthorize("hasAnyAuthority('sys:user:add','sys:user:edit')")
    @GetMapping(value = {"/form","/form/{id}"})
    public String form(@PathVariable(required = false) String id, Model model) {
        SysUser user = new SysUser();
        if(StringUtils.isNotEmpty(id)) {
            user = service.getById(id);
            List<SysRole> sysRoles = sysRoleMapper.selectRoleByUserId(user.getId() + "");
            user.setRoleList(sysRoles);
        }
        model.addAttribute("user",user);
        List<SysRole> sysRoles = sysRoleMapper.selectList(null);
        model.addAttribute("roleList",sysRoles);
        return HTML_PREFIX+"/user-form";
    }


    @PreAuthorize("hasAnyAuthority('sys:user:delete')")
    @ResponseBody
    @PostMapping(value = {"/{id}"})
    public Result delete(@PathVariable String id) {
        UpdateWrapper<SysUser> update = new UpdateWrapper<>();
        update.set("is_enabled",0);
        update.eq("id",id);
        service.update(update);
        return Result.ok();
    }


    @ResponseBody
    @PostMapping("/page")
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    public Result page(Page page, SysUser sysUser) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.eq("is_enabled",1);
        query.lambda().like(StringUtils.isNotEmpty(sysUser.getMobile()), SysUser::getMobile,sysUser.getMobile());
        IPage page1 = service.page(page, query);
        return Result.ok(page1);
    }


    @PostMapping
    @PreAuthorize("hasAnyAuthority('sys:user:add','sys:user:edit')")
    public String add(SysUser sysUser) {
        service.saveOrUpdateUser(sysUser);
        return "redirect:/user";
    }



}
